from django.shortcuts import render
from django.utils.http import urlquote

from utils.redis import redis_conn
from .models import *
from .serializers import *

from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet
from rest_framework.response import Response
from rest_framework import status

from django.http import HttpResponse,FileResponse
from django.db.models import Q
from django.db.models import F

import string
import random
import json
import os


# 请假模板
class LeaveViews(APIView):
    def post(self, request):
        try:
            leavetime = request.data.get("leavetime")
            leavecause = request.data.get("leavecause")
            leavetype = request.data.get("leavetype")
            print(request.data)

            type = Leave_Type.objects.filter()
            type_ser = LeaveTypeSer(type, many=True).data
            print(type_ser)
            for type_name in type_ser:
                print(type_name)
                print(leavetype)
                if type_name.get("type_name") == leavetype:
                    leavetype = type_name.get("id")
                    print("asd",leavetype)
            data = {
                "cause": leavecause,
                "leave_type": leavetype,
                "leavetime": leavetime,
                "type": 1,
            }
            ser = LeaveSer(data=data)
            if not ser.is_valid():
                return Response({"code": status.HTTP_400_BAD_REQUEST,"msg": ser.errors})

            Leave.objects.create(cause=leavecause, begin_time=leavetime, leave_type_id=leavetype, type_id=1)
            return Response({"code": status.HTTP_200_OK, "msg":"添加成功"})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})


# 借款模板
class LoanViews(APIView):
    def post(self, request):
        try:
            loantime = request.data.get("loantime")
            loancause = request.data.get("loancause")
            maney = request.data.get("money")
            print(request.data)

            data = {
                "begin_time": loantime,
                "cause": loancause,
                "money": maney,
                "type": 2,
            }

            ser = MoneySer(data=data)
            if not ser.is_valid():
                return Response({"code": status.HTTP_400_BAD_REQUEST,"msg": ser.errors})
            Money.objects.create(begin_time=loantime,cause=loancause,money=maney,type_id=2)
            return Response({"code": status.HTTP_200_OK, "msg":"添加成功"})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})


# 出差模板
class TravelViews(APIView):
    def post(self, request):
        try:
            traveltime = request.data.get("traveltime")
            destination = request.data.get("destination")
            travelcause = request.data.get("travelcause")
            travelentourage = request.data.get("travelentourage")
            print(request.data)
            data = {
                "cause": travelcause,
                "begin_time": traveltime,
                "address": destination,
                "peer":travelentourage,
                "type": 2,
            }
            ser = TravelSer(data=data)
            if not ser.is_valid():
                return Response({"code": status.HTTP_400_BAD_REQUEST,"msg": ser.errors})
            Travel.objects.create(cause = travelcause,begin_time= traveltime,address= destination,peer=travelentourage,type_id=2)
            return Response({"code": status.HTTP_200_OK,"msg": "添加成功"})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR,"msg": "服务器错误"})


# 转正模板
class PositiveViews(APIView):
    def post(self, request):
        try:
            positivetime = request.data.get("positivetime")
            appraisal = request.data.get("appraisal")
            print(request.data)
            data = {
                "cause": appraisal,
                "begin_time": positivetime,
                "type": 4,
            }
            ser = FormalSer(data=data)
            if not ser.is_valid():
                return Response({"code": status.HTTP_400_BAD_REQUEST,"msg": ser.errors})
            Formal.objects.create(cause = appraisal, type_id=2, begin_time=positivetime)
            return Response({"code": status.HTTP_200_OK,"msg": "添加成功"})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR,"msg": "服务器错误"})


# 5
# 用车模板
class BycarViews(APIView):
    def post(self, request):
        try:
            bycartime = request.data.get("bycartime")
            bycarstart = request.data.get("bycarstart")
            bycardestination = request.data.get("bycardestination")
            bycartype = request.data.get("bycartype")
            bycarcode = request.data.get("bycarcode")
            print(request.data)


            vehicle = Vehicle.objects.all()
            vehicle_ser = VehicleSer(vehicle, many=True).data
            plate = Plate.objects.all()
            plate_ser = PlateSer(plate, many=True).data

            for vehicle in vehicle_ser:
                print(vehicle)
                print(bycartype)
                if vehicle.get("vehicle_name") == bycartype:
                    bycartype = vehicle.get("id")

            for plate in plate_ser:
                print(plate)
                print(bycarcode)
                if plate.get("plate_name") == bycarcode:
                    bycarcode = plate.get("id")

            data = {
                "begin_time":bycartime,
                "start":bycarstart,
                "end":bycardestination,
                "vehicle":bycartype,
                "plate":bycarcode,
                "type":5
            }

            ser = CarSer(data=data)
            if not ser.is_valid():
                return Response({"code": status.HTTP_400_BAD_REQUEST,"msg": ser.errors})

            Car.objects.create(begin_time=bycartime,start=bycarstart,end=bycardestination,vehicle_id=bycartype,plate_id=bycarcode,type_id=5)
            return Response({"code": status.HTTP_200_OK, "msg":"添加成功"})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR, "msg":"服务器错误"})


# 报销模板
class ReimbursementViews(APIView):
    def post(self, request):
        try:
            reimbursedsum = request.data.get("reimbursedsum")
            reimbursedreason = request.data.get("reimbursedreason")
            materials = request.data.get("materials")
            print(request.data)
            data = {
                "cause": reimbursedreason,
                "voucher": materials,
                "money": reimbursedsum,
                "type": 6,
            }
            ser = FormalSer(data=data)
            if not ser.is_valid():
                return Response({"code": status.HTTP_400_BAD_REQUEST,"msg": ser.errors})
            Expense.objects.create(cause = reimbursedreason, type_id=6, voucher=materials, money=reimbursedsum)
            return Response({"code": status.HTTP_200_OK,"msg": "添加成功"})
        except Exception as e:
            print(e)
            return Response({"code": status.HTTP_500_INTERNAL_SERVER_ERROR,"msg": "服务器错误"})


class TopFormView(APIView):
    def post(self,request):
       # try:
        files = request.FILES.get('myfile')
        print("files>>>>>>>>>>>>>", files, type(files))
        files = str(files)
        print("str", files)
        material = Material.objects.filter(materialname=files).count()

        if material != 0:
            return Response({"code": status.HTTP_204_NO_CONTENT, 'msg': '存在'})
        print("asdfsadfsadfsd")

        # for f in files:
        file_info = Material.objects.create(materialname=files, materialurl=os.path.join('C:\\Users\Lenovo\Desktop', files))
        file_info.save()
                # 上传
        destination = open(os.path.join("C:\\Users\Lenovo\Desktop", files), 'wb+')
        print(files)
        for chunk in files.chunks():
            destination.write(chunk)
        destination.close()

        return Response({"code":status.HTTP_204_NO_CONTENT,'msg':'存入成功','data':destination.name})


class CLViews(APIView):
    def cl(self, request):
        file_info = Material.objects.get(id=id)
        print('下载的文件名：' + file_info.materialname)
        file = open(file_info.url,'rb')
        response = FileResponse(file)
        files = response['Content-Disposition'] = 'attachment;filename="%s"' % urlquote(file_info.material_name)
        return Response({"code": status.HTTP_200_OK,'msg': '下载成功','data': files})




































